/**
 * 新版文档管理模块
 * 
 * @Date: 2016-9-8
 * @author: Jackson wang
 * @version: 1.0
 * @since: 1.0
 */
define(['jquery', 'init','fullcalendar','fullcalendar_zh-cn','moment','bsUtil','formServ','codeDef',
			'bsButton','bsButtonEvent','datagridServ','bsMsgServ','bsAddressListEdit','bsGroupCustom'], 
	function($,init,fullcalendar,calendarLang,moment,bsUtil,formServ,codeDef,
				bsButton,bsButtonEvent,datagridServ,bsMsgServ,bsAddressListEdit,bsGroupCustom) {

	'use strict';

	var deptQryRoot = '/department/query/getList.action',
		deptQryUrl='/department/query/getTreeList.action',
		
		addressListQryUrl='/oaAddressList/query/getListDomainByDeptid.action',
		addressListSaveUrl='/oaAddressList/save.action',
		addressListDelUrl='/oaAddressList/del.action',
		
		//模块代码定义		
		
		moduCode = {
			//通讯录
			addr: 'oaAddressList',
			//分组管理
			group: 'groupCustom'
		},
		
		//当前模块(缺省为通讯录)
		currentModu = moduCode.addr,
		
		//当前选中行
		curent_selectRow,
		
		//编辑页面url
		addressListEditUrl='/oaAddressList/query/getPage.action?code=bsEditDlg'
	//js参数
	var jsParam
	
	//文档分类树dom对象,文档明细列表对象
	var $typegrid,$detailgrid
	
	//弹窗dom对象
	var $edit_window
	
	//选中类型对象
	var selectedDetp
	
	var subrootid = 'addr';
	var rootid = 'bs-address-list';
	
	var btn_container = rootid + ' .btn-container';
	
	var private_method = {
		
		bindTabShown:function(){
			var _el = $('#'+rootid + ' #addr-tab a')
			if(_el.length>0){
				
				_el.unbind('shown.bs.tab')
				_el.bind('shown.bs.tab',private_method.initTab)
			}
			
		}
		
		,
		initTab:function(e){
//			e.preventDefault();
//			$('#'+rootid + ' #addr-tab a').tab('show');
			
			//获取当前点击模块
			var _el = $(e.currentTarget);
			if(_el.length==1){
				var _id = _el.attr('href');
				if(_id){
					_id = _id.substr(1);
					currentModu = moduCode[_id];
					
					if(_id=='addr'){
						private_method.initAddr();
					}else{
						private_method.initGroup();
					}
				}
			}
			
		}
		,
		
		//初始化通讯录
		initAddr:function(){
			private_method.initTypeList();
			private_method.initAddressListBtn();
			private_method.initAddressList();
			
		}
		,
		//初始化分组管理
		initGroup:function(){
			bsGroupCustom.initPage();
		}
		,
		//重新绘制按钮
		/**
    	 * 更新按钮
    	 * @param _options.bizcode	业务编码
    	 * @param _options.btnType		按钮类型(list,edit,view)
    	 * @param _options.bizType	业务类型(0:normal,1:flow,2:audit)
    	 * @param _options.container 按钮容器对象
    	 */
    	redrawBtn:function(_options){
    		
    		
    		var _btn ;
    		if(_options && _options.btnType){    			
	    		_btn = bsButton.getBtn(_options);	    				
    		}    		
    		
    		$('#'+_options.container).empty();
    		
    		if(_btn){    			
    			$('#'+_options.container + ' button').unbind('click');    			
    			$('#'+_options.container).append(_btn);    			
    			//绑定按钮事件
    			$('#'+_options.container + ' button').bind('click',private_method.btnClick);
    		}
    		
    	}
    	
    	,
    	btnClick:function(e){
    		
    		init.applyBtnEvt({btnEvt:e,btnConfig:btnEvent})
//    		bsMsgServ.msgSlide();
    	}
		,
		/**
		 * 初始化科室列表
		 */
		initTypeList:function(){ 
			selectedDetp = null;
			var typeParam = {
				rownumbers:true,
				animate: true,									
				striped:true,
				border:true,
				//singleSelect:false,
				idField: 'id',
				treeField: 'name',	
				queryParams: {id:null},
				fitColumns: true,
				url : '/' +init.getSite() + deptQryUrl,
				onClickRow:private_method.getAddressList,
				columns:[[
					{field:'name',title:'科室名称',width:100,halign:'center'}
				]]
				
			}
			
			$typegrid=$('#'+rootid + ' .tg-tree').treegrid(typeParam);
			
//			$typegrid.treegrid('options').url =  '/'+init.getSite() + deptQryUrl;
		}
		,
		/**
		 * 初始化明细列表
		 */
		initAddressList:function(_options){
			var _detailParam = {				
				url : '/'+init.getSite() + addressListQryUrl,
				height:init.getGridHeight(),
				rownumbers:true,
				animate: true,									
				striped:true,
				border:true,
				//singleSelect:false,
				idField: 'id',									
				fitColumns: true,
				checkOnSelect:true,
				pagination : true,
				selectOnCheck:true,
				onDblClickRow	: private_method.dblClick,
				columns:[[
					{field:'ck',checkbox:true},
					{field:'id',title:'用户编码',width:40,halign:'center'},       
					{field:'loginname',title:'登录账号',width:40,halign:'center'},        
					{field:'name',title:'用户姓名',width:50,halign:'center'},        
					{field:'deptName',title:'部门名称',width:50,halign:'center'} ,
					{field:'position',title:'职位',width:50,halign:'center'} ,
					{field:'workphone',title:'工作电话',width:60,halign:'center'},
					{field:'mobile',title:'移动电话',width:60,halign:'center'},        
					{field:'email',title:'邮箱',width:60,halign:'center'},        
					{field:'qq',title:'QQ',width:60,halign:'center'} ,
					{field:'weixin',title:'微信',width:60,halign:'center'} 					
				]]
			}
			
			_detailParam = $.extend(_detailParam,_options);
			$detailgrid = $('#'+rootid + ' #'+ subrootid +' .dg-list').datagrid(_detailParam);	
			
			
		},
		
		initAddressListBtn:function(){
			if(window.console){
				console.log(' detail list button init ...')
			}
			var _btn = bsButton.getBtn({bizcode:moduCode.addr,btnType:'list',bizType:2});
			
			var _c = $('#'+rootid + ' .btn-container')
			if(_c.length>0){
				
				_c.empty();
			
				if(_btn){
					_c.append(_btn);
					//绑定按钮点击事件
					private_method.bind_btn_click();
				}							
				
			}
			
			//绑定tab显示事件
			private_method.bindTabShown();
			
		}
		,
		//获取文档明细列表
		getAddressList:function(rowData){
			selectedDetp = rowData;
			
			$detailgrid = $('#'+rootid + ' .list-detail')
			
			//判断是刷新还是初始化组织结构树
			if($detailgrid.length!=1){
				//初始化组织结构树
				var _c = $('#' + rootid + ' .addr-list')
				_c.empty();
				_c.append('<div class="list-detail dg-list"></div>');
				$detailgrid = $('#'+rootid + ' .list-detail')
				private_method.initAddressList({queryParams:{deptid:rowData.id}})
				private_method.initAddressListBtn();
			}else{
				//刷新组织结构树
				$detailgrid.datagrid('load',{deptid:rowData.id})
			}
		}
		,
		bind_btn_click:function(e){
			var _btn = $('#'+rootid + ' button')
			if(_btn.length>0){
				_btn.unbind('click');
				_btn.bind('click',private_method.btn_listenner);
			}
		}
		,
		btn_listenner:function(e){
			init.applyBtnEvt({btnEvt:e,btnConfig:btnEvent});
		}
		
		
		
		,
		
		getCheckData:function(records){
			var _data,tid
			if(records.length==1){
				_data = {id:records[0].id};	
			}else{
				$.each(records,function(i,el){
					tid=!tid?el.id:tid+','+el.id
				})
				_data = {ids:tid}
			}
			
			return _data;
		}
		,
		
		dblClick : function(index,row){
			var _grid = $('#'+rootid + ' .list-detail')
			
			if(_grid.length == 1){
				_grid.datagrid('clearSelections');
				_grid.datagrid('selectRow',index);
				curent_selectRow = row;
			}
			var _btn = $('#' + rootid + ' [btn-type="listEdit"]');
    		_btn.trigger('click');
		}
		,
		initEdit:function(){
			private_method.redrawBtn({
    			bizcode: currentModu,
    			btnType: 'edit',
    			container: btn_container
    		})
    				
			
			//定位form对象
			var $form = $('#'+rootid + ' .main-form')								
			
			var selectedRecord = curent_selectRow;
			if(selectedRecord){
				$form.form('load',selectedRecord);						
			}		
			
			//绑定按钮事件
			private_method.bind_btn_click();
		}
	}
	
	var btnEvent =  {
		listAdd:function(e){
			if(!selectedDetp){
				bsMsgServ.errorSlide('请选择部门');
				$(e.currentTarget).removeClass('disabled');
				return ;
			}
			
			$('#'+rootid + ' .dg-list').datagrid('clearSelections');
			btnEvent.editExecute({evt:e,flag:false});
		}
		,
		listDel:function(e){
			
			var _data,tid
			
			var _grid = $('#'+rootid + ' .dg-list')
			var records = _grid.datagrid('getSelections');
			if(records.length>0){
				var selectedRecord = records[0];
				//判断审核标志
				
				if(!bsUtil.checkStatus({records:records,status:0})){								
					bsMsgServ.warnSlide('已审核记录不能进行删除操作！');
					$(e.currentTarget).removeClass('disabled');
					return
				}
				
				
				
				if(records.length==1){
					_data = {id:selectedRecord.id};	
				}else{
					$.each(records,function(i,el){
						tid=!tid?el.id:tid+','+el.id
					})
					_data = {ids:tid}
				}
				
			}else{
				bsMsgServ.warnSlide('请选择要删除的记录');
				$(e.currentTarget).removeClass('disabled');
				return
			}
								
			$.messager.confirm('警告', '确定执行删除操作?', function(r){
						
				if( r){					
					$.ajax({
						url:'/'+init.getSite()+'/oaAddressList/del.action',
					 	contentType:'form',
					 	data:_data,
					 	success:function(){						 		
							_grid.datagrid('clearSelections');
							_grid.datagrid('reload');
							bsMsgServ.msgSlide('删除记录操作成功！');
							$(e.currentTarget).removeClass('disabled');
					 	}
					 	,
					 	failure:function(){
					 		
					 		bsMsgServ.errorSlide(
					 			codeDef.getConfig({
					 				type:'operate',code:'error'
					 			})
					 		);
					 		$(e.currentTarget).removeClass('disabled');
					 	}
					})
				}
			})
		}
		,
		listEdit:function(e){
			var _record = $('#' + rootid + ' .dg-list').datagrid('getSelections');
    		
    		if(_record.length==1){
	    		var _url = '/common/query/getBizPage.action?subSystem=oa&code=bsEditDlg&module='+moduCode.addr
	    		bsButtonEvent.add({
	    			url:_url,
	    			container:'bs-address-list .addr-list',
	    			formInit:null,
	    			data:_record,
	    			evt:e
	    		})	 
	    		
	    		
	    		//暂存当前选中行
	    		curent_selectRow = _record[0];
    		}else{
    			if(_record.length>1){
    				bsMsgServ.warnSlide('您选择了多条记录，请鼠标双击想编辑的行.')	
    			}else{
    				bsMsgServ.warnSlide('请选择想操作的行')	
    			}
    			$(e.currentTarget).removeClass('disabled');
    		}
		}
		
		
		,
				
		/**
		 * 提交审核
		 */
		listSubmit:function(e){
			
			private_method.exeAudit({auditType:'submit',evt:e})
			
		},
		/**
		 * 审核通过
		 */
		listPermit:function(e){
			
			private_method.exeAudit({auditType:'permit',evt:e})
		},
		/**
		 * 审核未通过
		 */
		listDenied:function(e){
			
			private_method.exeAudit({auditType:'denied',evt:e})
		},
		
		editSave : function(e) {
			
			if(window.console){
				console.log(' save fired ...')	
			}
			var _f = $('#'+rootid + ' .main-form')
			
//			if(!private_method.validateForm(e)){
//				//提示和释放按钮在函数中处理
//				
//				//form验证未通过，中断函数执行并返回
//				return
//			}			
			
			var formData = formServ.getDataObj({
						form : _f
					});					
			
			$.ajax({
				url:'/'+init.getSite()+'/'+ moduCode.addr +'/save.action',
				data:$.toJSON(formData),
				contentType:'appliction/json;charset=utf-8',
				type:'post',
				dataType:'json',
				success:function(data){
					if(data){						
						
						//刷新form
						$('#'+rootid + ' .main-form').form('load',data);
						
					}
					bsMsgServ.msgSlide(codeDef.getConfig({
						type:'operate',
						code:'success'
					}))
					
					bsUtil.updateIssueBadge();
					$(e.currentTarget).removeClass('disabled');
				}
				,
				error:function(){
					bsMsgServ.errorSlide(codeDef.getConfig({
						type:'operate',
						code:'error'
					}))
					$(e.currentTarget).removeClass('disabled');
				}
			})
							
		}
		,
		editCancel	:function(){
			
			private_method.getAddressList(selectedDetp)
		}
	}
	
	var public_method = {
		
		//初始化函数
		initPage:function(){
			private_method.initAddr();
		}
		,
		
		initEdit:function(){
					
			//初始化编辑页面按钮
			private_method.initEdit();
				
		}
		,
		//脚本打开页面
		openPage:function(_options){
			var _url = '/'+init.getSite()+'/common/query/getPage.action?code=userSelect';
			
			var _container = $('#user-select-pop')
			
			if(_container.length<=0){
				$('body').append('<div id="user-select-pop"></div>');
			}
			
			_container = $('#user-select-pop')
			_container.load(_url);
		}
		,
		destroy:function(){
			
			//解绑tab点击事件
			var _el = $('#'+rootid + ' #addr-tab a')
			if(_el.length>0){				
				_el.unbind('click')				
			}
			
			//解绑按钮事件
			var _btn = $('#'+rootid + ' button')
			if(_btn.length>0){
				_btn.unbind('click');
			}
		}
	}
	
	
	return public_method;
});